<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入任务名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务信息" prop="info">
        <el-input
            v-model="queryParams.info"
            placeholder="请输入任务信息"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择任务类型" clearable>
          <el-option
              v-for="dict in device_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
              v-for="dict in device_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据量" prop="amount">
        <el-input
            v-model="queryParams.amount"
            placeholder="请输入数据量"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="国家" prop="country">
        <el-input
            v-model="queryParams.country"
            placeholder="请输入国家"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['device:task:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['device:task:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['device:task:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['device:task:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="任务名" align="center" prop="name"/>
      <el-table-column label="任务信息" align="center" prop="info"/>
      <el-table-column label="任务类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="device_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="数据量" align="center" prop="amount"/>
      <el-table-column label="任务时长(天)" align="center" prop="days"/>
      <el-table-column label="执行时间段" align="center" prop="p3"/>
      <el-table-column label="国家" align="center" prop="country"/>
      <el-table-column label="每分钟请求量" align="center" prop="p1"/>
      <el-table-column label="任务配置" :show-overflow-tooltip='true' align="center" prop="config"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="完成量" align="center" prop="p2"/>
      <!--      <el-table-column label="备用字段" align="center" prop="p4" />-->
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['device:task:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['device:task:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改设备任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名" prop="name">
          <el-input v-model="form.name" placeholder="请输入任务名"/>
        </el-form-item>
        <el-form-item label="任务信息" prop="info">
          <el-input v-model="form.info" placeholder="请输入任务信息"/>
        </el-form-item>
        <el-form-item label="任务类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择任务类型">
            <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择任务状态">
            <el-option
                v-for="dict in device_status"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数据量"/>
        </el-form-item>
        <el-form-item label="已完成" prop="p2">
          <el-input v-model="form.p2" placeholder="请输入已完成数量"/>
        </el-form-item>
        <el-form-item label="任务时间" prop="days">
          <!--          <el-input v-model="form.days" placeholder="任务时间"/>-->
          <el-date-picker
              v-model="date"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="执行时间段" prop="p3">
          <!--          <el-input v-model="form.p3" placeholder="请输入任务时长(天)"/>-->
          <el-time-select
              v-model="form.startTime"
              style="width: 150px"
              class="mr-4"
              placeholder="Start time"
              start="00:00"
              step="00:15"
              end="23:59"
          />
          <el-time-select
              v-model="form.endTime"
              style="width: 150px;margin-left: 20px;"
              :min-time="form.startTime"
              placeholder="End time"
              start="00:00"
              step="00:15"
              end="23:59"
          />
          <!--          <el-time-picker-->
          <!--              v-model="time"-->
          <!--              format="HH:mm"-->
          <!--              value-format="HH:mm"-->
          <!--              is-range-->
          <!--              range-separator="To"-->
          <!--              start-placeholder="开始时间"-->
          <!--              end-placeholder="结束时间"-->
          <!--          />-->
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-input v-model="form.country" placeholder="请输入国家"/>
        </el-form-item>
        <el-form-item label="每分钟请求量" prop="p1">
          <el-input v-model="form.p1" placeholder="每分钟请求量"/>
        </el-form-item>
        <el-form-item label="业务配置" prop="config">
          <el-input style="min-height: 100px;" v-model="form.config" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>

        <!--        <el-form-item label="备用字段" prop="p2">-->
        <!--          <el-input v-model="form.p2" placeholder="请输入备用字段" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备用字段" prop="p3">-->
        <!--          <el-input v-model="form.p3" placeholder="请输入备用字段" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备用字段" prop="p4">-->
        <!--          <el-input v-model="form.p4" placeholder="请输入备用字段" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="更新时间" prop="updatedTime">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.updatedTime"-->
        <!--            type="date"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--            placeholder="请选择更新时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="创建时间" prop="createdTime">-->
        <!--          <el-date-picker clearable-->
        <!--            v-model="form.createdTime"-->
        <!--            type="date"-->
        <!--            value-format="YYYY-MM-DD"-->
        <!--            placeholder="请选择创建时间">-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task">
import {listTask, getTask, delTask, addTask, updateTask} from "@/api/device/task";

const {proxy} = getCurrentInstance();
const {device_status, device_type} = proxy.useDict('device_status', 'device_type');

const taskList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const time = ref([
  '',
  ''
])
const date = ref([
  '',
  ''
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    info: null,
    type: null,
    status: null,
    config: null,
    amount: null,
    days: null,
    country: null,
    p1: null,
    p2: null,
    p3: null,
    p4: null,
    updatedTime: null,
    createdTime: null
  },
  rules: {
    name: [
      {required: true, message: "任务名不能为空", trigger: "blur"}
    ],
    // type: [
    //   { required: true, message: "任务类型0:1不能为空", trigger: "change" }
    // ],
    // status: [
    //   { required: true, message: "任务状态0:1:2:3不能为空", trigger: "change" }
    // ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询设备任务列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    info: null,
    type: null,
    status: null,
    remark: null,
    config: null,
    amount: null,
    days: null,
    country: null,
    p1: null,
    p2: null,
    p3: null,
    p4: null,
    updatedTime: null,
    createdTime: null
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getTask(_id).then(response => {
    form.value = response.data;
    if (form.value.days && form.value.days.split(',').length > 1) {
      date.value = form.value.days?.split(',')
    }
    if (form.value.p3 && form.value.p3.split(',').length > 1) {
      let tms = form.value.p3?.split(',')
      form.value.startTime = convertMinutesToTimeString(tms[0])
      form.value.endTime = convertMinutesToTimeString(tms[1])
    }

    open.value = true;
    title.value = "修改设备任务";
  });
}

function convertMinutesToTimeString(minutes) {
  // 计算小时和分钟
  let hours = Math.floor(minutes / 60);
  let mins = minutes % 60;

  // 手动补零操作
  let hoursString = (hours < 10 ? '0' : '') + hours;
  let minsString = (mins < 10 ? '0' : '') + mins;

  // 返回格式化字符串
  return `${hoursString}:${minsString}`;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      let st = form.value.startTime
      let en = form.value.endTime
      console.log(st + "--" + en);
      if (st && en) {
        st = st.split(':')
        st = parseInt(st[0]) * 60 + parseInt(st[1]);
        en = en.split(':')
        en = parseInt(en[0]) * 60 + parseInt(en[1]);
        form.value.p3 = st + "," + en;
      } else {
        form.value.p3 = 0 + "," + 0;
      }
      if (date.value) {
        let st = date.value[0]
        let en = date.value[1]
        console.log(st + "--" + en);
        if (st && en) {
          form.value.days = st + "," + en;
        } else {
          form.value.days = ''
        }
      } else {
        form.value.days = ''
      }
      date.value = ["", ""]
      form.value.startTime = ""
      form.value.endTime = ""
      if (form.value.id != null) {
        updateTask(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTask(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除设备任务编号为"' + _ids + '"的数据项？').then(function () {
    return delTask(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('device/task/export', {
    ...queryParams.value
  }, `task_${new Date().getTime()}.xlsx`)
}

getList();
</script>
